<template>
  <div>
    <el-row :gutter="20" class="patientInfo" v-if="clinicNo">
      <el-col :span="5">
        <p class="grid-content bg-purple">门诊号:{{clinicNo}}</p>
      </el-col>
      <el-col :span="2">
        <p class="grid-content bg-purple">姓名:{{patient.name}}</p>
      </el-col>
      <el-col :span="2">
        <p class="grid-content bg-purple">性别:{{patient.gender | gender}}</p>
      </el-col>
      <el-col :span="2">
        <p class="grid-content bg-purple">年龄:{{patient.birth | age}}</p>
      </el-col>
      <el-col :span="4">
        <p class="grid-content bg-purple">联系电话:{{patient.tel}}</p>
      </el-col>
      <el-col :span="4">
        <p class="grid-content bg-purple">住址:{{patient.addr}}</p>
      </el-col>
      <el-button
        type="primary"
        v-if="!record.finish"
        @click="completeTreat"
        style="margin-top: 2px;float: right;margin-right: 20px"
      >完成接诊
      </el-button>
      <el-button
        type="info"
        v-if="!record.finish"
        style="margin-top: 2px;float: right;margin-right: 5px"
        @click="addInspect"
      >添加检查
      </el-button>
    </el-row>

    <el-tabs type="border-card" v-model="activeName" :beforeLeave="BeforeLeave">
      <el-tab-pane
        v-for="(item, index) in list"
        :key="item.id + '_' + index"
        :label="item.project"
        :name="item.projectName"
      >
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{item.project}}</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              v-if="!record.finish"
              @click="validate(item)"
            >保存{{item.projectDesc}}
            </el-button>

            <el-button
              style="float: right; padding: 3px 0;margin: 0 5px"
              type="text"
              v-if="!record.finish"
              @click="setTemplate(item)"
            >保存为模板
            </el-button>

            <el-button
              style="float: right; padding: 3px 0;margin: 0 5px"
              type="text"
              v-if="!record.finish"
              @click="setVal(item)"
            >导入模板数据
            </el-button>
          </div>
          <el-row>
            <form-item :ref="item.projectName" :list="item.children" :clinicNo="clinicNo"
                       :isFinish="record.finish"></form-item>
          </el-row>
          <!--暂时不单独引入处方信息,合并到检查单中-->
          <el-row v-if="item.seq === 3" v-show="dialogPrescriptionVisible">
            <el-col :span="2" class="tit2">
              <el-button
                type="info"
                :disabled="record.finish"
                @click="addMyPrescription(item)"
              >视光处方
              </el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-tab-pane>
      <el-tab-pane name="随访" label="随访">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>随访信息</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="dialogVisible = true"
            >新增随访记录
            </el-button>
          </div>
          <div class="text item">
            <el-table :data="followList" border fit highlight-current-row style="width: 100%;">
              <el-table-column label="id" prop="id" align="center" width="100">
                <template slot-scope="{ row }">
                  <span>{{ row.id }}</span>
                </template>
              </el-table-column>

              <el-table-column label="随访记录" prop="content" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.content }}</span>
                </template>
              </el-table-column>

              <el-table-column label="随访建议" prop="conclusion" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.conclusion }}</span>
                </template>
              </el-table-column>

              <el-table-column label="随访方式" prop="kind" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.kind | kindFormat }}</span>
                </template>
              </el-table-column>

              <el-table-column label="随访状态" prop="status" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.status | statusFormat }}</span>
                </template>
              </el-table-column>

              <el-table-column label="预约时间" prop="appointmentTime" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.appointmentTime | timeFormat }}</span>
                </template>
              </el-table-column>
            </el-table>

            <el-dialog :visible.sync="dialogVisible" @close="onClose" title="新增随访">
              <el-form
                ref="followForm"
                :model="followData"
                :rules="followRules"
                size="medium"
                label-width="100px"
              >
                <el-form-item label="随访记录" prop="content">
                  <el-input
                    v-model="followData.content"
                    type="textarea"
                    placeholder="请输入随访记录"
                    :autosize="{minRows: 4, maxRows: 4}"
                    :style="{width: '100%'}"
                  ></el-input>
                </el-form-item>
                <el-form-item label="随访建议" prop="conclusion">
                  <el-input
                    v-model="followData.conclusion"
                    type="textarea"
                    placeholder="请输入随访建议"
                    :autosize="{minRows: 4, maxRows: 4}"
                    :style="{width: '100%'}"
                  ></el-input>
                </el-form-item>
                <el-form-item label="随访方式" prop="kind">
                  <el-select
                    v-model="followData.kind"
                    placeholder="请选择随访方式"
                    clearable
                    :style="{width: '100%'}"
                  >
                    <el-option
                      v-for="(item, index) in kindOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="随访状态" prop="status">
                  <el-select
                    v-model="followData.status"
                    placeholder="请选择随访状态"
                    clearable
                    :style="{width: '100%'}"
                  >
                    <el-option
                      v-for="(item, index) in statusOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="预约时间" prop="appointmentTime">
                  <el-date-picker
                    type="datetime"
                    v-model="followData.appointmentTime"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :style="{width: '100%'}"
                    placeholder="请选择预约时间"
                    clearable
                  ></el-date-picker>
                </el-form-item>
                <el-form-item size="large">
                  <el-button type="primary" @click="submitForm">提交</el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane name="prescription" label="处方">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{this.prescription.kind | prescriptionKind}}处方</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              v-show="!record.finish && !this.prescription.id"
              @click="addPrescription"
            >新增处方
            </el-button>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              v-show="!record.finish && this.prescription.id"
              @click="addProduct"
            >保存处方
            </el-button>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              v-show="!record.finish && this.prescription.id"
              @click="getProduct"
            >添加商品
            </el-button>
          </div>
          <div class="text item">
            <el-table :data="productList" border fit highlight-current-row style="width: 100%;">
              <el-table-column label="产品编码" prop="productCode" align="center">
                <template slot-scope="{row}">
                  <span>{{row.productCode}}</span>
                </template>
              </el-table-column>
              <el-table-column label="产品名称" prop="productName" align="center">
                <template slot-scope="{row}">
                  <span>{{row.productName}}</span>
                </template>
              </el-table-column>

              <el-table-column label="单位" prop="unit" align="center">
                <template slot-scope="{row}">
                  <span>{{row.unit}}</span>
                </template>
              </el-table-column>

              <el-table-column label="库存" prop="stockNum" align="center" v-if="!record.finish">
                <template slot-scope="{row}">
                  <span>{{row.stockNum}}</span>
                </template>
              </el-table-column>

              <!--<el-table-column label="单价" prop="univalent" align="center" v-if="!record.finish">
                <template slot-scope="{row}">
                  <span>{{row.univalent}}</span>
                </template>
              </el-table-column>-->

              <el-table-column label="需求数量" prop="needNum" header-align="center">
                <template slot-scope="{row,$index}">
                  <el-slider
                    v-if="showEdit[$index]"
                    v-model="row.needNum"
                    style="width: 100%"
                    :step="1"
                    :min="0"
                    :max="row.stockNum"
                  ></el-slider>
                  <span v-if="!showEdit[$index]">{{row.needNum}}</span>
                </template>
              </el-table-column>

              <el-table-column label="用法说明" prop="usage" header-align="center">
                <template slot-scope="{row,$index}">
                  <input
                    class="edit-cell"
                    v-if="showEdit[$index]"
                    v-model="row.usage"
                    style="width: 100%"
                  />
                  <span v-if="!showEdit[$index]">{{row.usage}}</span>
                </template>
              </el-table-column>

              <el-table-column label="用法部位" prop="part" header-align="center">
                <template slot-scope="{row,$index}">
                  <input
                    class="edit-cell"
                    v-if="showEdit[$index]"
                    v-model="row.part"
                    style="width: 100%"
                  />
                  <span v-if="!showEdit[$index]">{{row.part}}</span>
                </template>
              </el-table-column>

              <el-table-column label="频次" prop="frequency" header-align="center">
                <template slot-scope="{row,$index}">
                  <input
                    class="edit-cell"
                    v-if="showEdit[$index]"
                    v-model="row.frequency"
                    style="width: 100%"
                  />
                  <span v-if="!showEdit[$index]">{{row.frequency}}</span>
                </template>
              </el-table-column>

              <el-table-column label="天数" prop="days" header-align="center">
                <template slot-scope="{row,$index}">
                  <input
                    class="edit-cell"
                    v-if="showEdit[$index]"
                    v-model="row.days"
                    style="width: 100%"
                  />
                  <span v-if="!showEdit[$index]">{{row.days}}</span>
                </template>
              </el-table-column>

              <el-table-column fixed="right" label="操作" v-if="!record.finish" header-align="center">
                <template slot-scope="{row,$index}">
                  <el-button
                    type="text"
                    size="small"
                    @click.native="handleUpdate($index, row)"
                    v-if="showBtn[$index]"
                  >更新
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click.native="handleCancel($index, row)"
                    v-if="showBtn[$index]"
                  >取消
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click.native="handleEdit($index, row)"
                    v-if="!showBtn[$index]"
                  >编辑
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click.native="handleDelete($index, row)"
                    v-if="!showBtn[$index]"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-dialog :visible.sync="dialogPreVisible" title="新增处方">
              <el-form
                ref="prescriptionForm"
                :model="prescription"
                size="medium"
                label-width="100px"
              >
                <el-form-item label-width="150px" label="处方类型 " prop="kind">
                  <el-select
                    v-model="prescription.kind"
                    placeholder="请选择处方类型 "
                    clearable
                    :style="{width: '100%'}"
                  >
                    <el-option
                      v-for="(item, index) in prescriptionType"
                      :key="index"
                      :label="item.key"
                      :value="item.val"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item size="large">
                  <el-button type="primary" @click="submitPrescription">提交</el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>

            <el-dialog :visible.sync="dialogProductVisible" title="产品查询">
              <Product :list="productList"></Product>
            </el-dialog>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane name="fee" label="其他收费" v-if="false">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>收费</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="dialogVisible = true"
            >新增收费
            </el-button>
          </div>
          <div class="text item">
            <el-table :data="followList" border fit highlight-current-row style="width: 100%;">
              <el-table-column label="id" prop="id" align="center" width="100">
                <template slot-scope="{ row }">
                  <span>{{ row.id }}</span>
                </template>
              </el-table-column>

              <el-table-column label="随访记录" prop="content" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.content }}</span>
                </template>
              </el-table-column>

              <el-table-column label="随访建议" prop="conclusion" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.conclusion }}</span>
                </template>
              </el-table-column>

              <el-table-column label="随访方式" prop="kind" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.kind | kindFormat }}</span>
                </template>
              </el-table-column>

              <el-table-column label="随访状态" prop="status" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.status | statusFormat }}</span>
                </template>
              </el-table-column>

              <el-table-column label="预约时间" prop="appointmentTime" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.appointmentTime | timeFormat }}</span>
                </template>
              </el-table-column>
            </el-table>

            <el-dialog :visible.sync="dialogVisible" @close="onClose" title="新增随访">
              <el-form
                ref="followForm"
                :model="followData"
                :rules="followRules"
                size="medium"
                label-width="100px"
              >
                <el-form-item label="随访记录" prop="content">
                  <el-input
                    v-model="followData.content"
                    type="textarea"
                    placeholder="请输入随访记录"
                    :autosize="{minRows: 4, maxRows: 4}"
                    :style="{width: '100%'}"
                  ></el-input>
                </el-form-item>
                <el-form-item label="随访建议" prop="conclusion">
                  <el-input
                    v-model="followData.conclusion"
                    type="textarea"
                    placeholder="请输入随访建议"
                    :autosize="{minRows: 4, maxRows: 4}"
                    :style="{width: '100%'}"
                  ></el-input>
                </el-form-item>
                <el-form-item label="随访方式" prop="kind">
                  <el-select
                    v-model="followData.kind"
                    placeholder="请选择随访方式"
                    clearable
                    :style="{width: '100%'}"
                  >
                    <el-option
                      v-for="(item, index) in kindOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="随访状态" prop="status">
                  <el-select
                    v-model="followData.status"
                    placeholder="请选择随访状态"
                    clearable
                    :style="{width: '100%'}"
                  >
                    <el-option
                      v-for="(item, index) in statusOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="预约时间" prop="appointmentTime">
                  <el-date-picker
                    type="datetime"
                    v-model="followData.appointmentTime"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :style="{width: '100%'}"
                    placeholder="请选择预约时间"
                    clearable
                  ></el-date-picker>
                </el-form-item>
                <el-form-item size="large">
                  <el-button type="primary" @click="submitForm">提交</el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <el-dialog :visible.sync="dialogInspectVisible" title="申请专科检查">
      <el-form ref="inspectForm" size="medium" label-width="100px">
        <el-form-item label="检查项目" prop="inspect">
          <el-checkbox-group v-model="inspectData" size="medium">
            <el-checkbox v-for="(item, index) in inspectList" :key="index"
                         :label="item.projectId">{{item.projectName}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="chooseInspect">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPrescriptionVisible" title="引用处方">
      <el-form ref="prescriptionForm" size="medium" label-width="100px">
        <el-form-item label="检查项目" prop="inspect">
          <el-checkbox-group v-model="prescriptionData" size="medium">
            <el-checkbox v-for="(item, index) in prescriptionList" :key="index"
                         :label="item.projectId">{{item.projectName}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="choosePrescription">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import Product from "@/components/Clinic/product";
  import FormItem from "@/components/Clinic/FormItem";
  import {getTree} from "@/utils/info-item-tree";
  import {getResults} from "@/utils/info-tree-array";

  import {
    getClinicTreat,
    getFollow,
    editFollow,
    getInspect,
    getInspectInfo,
    addTreatResult,
    makePrescription,
    editPrescriptionStore,
    completeTreat
  } from "@/api/treat";

  import {searchDict} from "@/api/dict";
  import {saveTemplate} from "@/api/emrSetting";

  export default {
    name: "treat",
    components: {
      FormItem,
      Product
    },
    created() {
      window.app = this;
      if (!this.$route.params.clinicNo) {
        this.$router.push({
          name: "treatRecord"
        });
      } else {
        // this.list = getTree(data);
        this.clinicNo = this.$route.params.clinicNo;
        this.treat = this.$route.params.treat;
        this.patient = this.$route.params.patient;
        getClinicTreat({clinicNo: this.clinicNo, treatId: this.treat}).then(
          response => {
            console.log(response);
            if (response.code === 200) {
              this.dataList = response.page.list;
              this.list = getTree(response.page.list);
              this.list.forEach(item => {
                item.isFinish = 0
              })
              if (response.record) {
                this.record = response.record;
                this.productList = response.products.filter(function (p) {
                  p.needNum = p.num;
                  p.stockNum = p.num;
                  app.prescription.id = p.prescriptionId;
                  return true;
                });
                if (!this.record.finish) {
                  getInspect({"seq": 3, "pageSize": 100}).then(resp => {
                    if (resp.code === 200) {
                      this.inspectList = resp.page.list
                    }
                  });
                  getInspect({"seq": 4, "pageSize": 100}).then(resp => {
                    if (resp.code === 200) {
                      this.prescriptionList = resp.page.list
                    }
                  });
                }
              }

              if (this.record.finish) {
                //隐藏类目为空的信息
                let _that = this;
                this.list = this.list.filter(function (item) {
                  _that.hideItem(item)
                  return item.children.length > 0;
                })
              }

              this.activeName =
                this.list.length > 0 ? this.list[0].projectName : "";

              this.tabName = this.list.map(function (t) {
                return t.projectName;
              })

            }
          }
        );
        searchDict({key: "处方类型"}).then(response => {
          if (response.code === 200) {
            this.prescriptionType = response.page.filter(function (item) {
              return item.available;
            });
          }
        });
      }
    },
    data() {
      return {
        tabName: [],
        map: {},
        targetProjectId: "",
        prescriptionList: [],
        prescriptionData: [],
        dialogPrescriptionVisible: false,
        inspectData: [],
        dialogInspectVisible: false,
        inspectList: [],
        record: {
          finish: false
        },
        showEdit: [], //显示编辑框
        showBtn: [],
        showBtnOrdinary: true,
        productList: [],
        dialogProductVisible: false,
        dialogPreVisible: false,
        prescription: {},
        prescriptionType: [],
        followList: [],
        dialogVisible: false,
        patient: {
          id: 9,
          name: "caine",
          gender: 1,
          birth: "1999-12-30",
          addr: "string",
          tel: "15999802003",
          idCard: "445102199010252311",
          remark: "sys",
          version: 0,
          createDate: "2020-02-27T17:29:38.000+0000",
          createBy: "sys:admin",
          lastUpdateBy: null,
          lastUpdateDate: "2020-04-08T14:32:27.000+0000",
          del: false
        },
        clinicNo: "010520042200271044",
        treat: 63,
        activeName: "",
        dataList: [],
        list: [],
        followData: {
          content: null,
          conclusion: null,
          kind: null,
          status: null,
          appointmentTime: ""
        },
        followRules: {
          content: [
            {
              required: true,
              message: "请输入随访记录",
              trigger: "blur"
            }
          ],
          conclusion: [],
          kind: [
            {
              required: true,
              message: "请选择随访方式",
              trigger: "change"
            }
          ],
          status: [
            {
              required: true,
              message: "请选择随访状态",
              trigger: "change"
            }
          ],
          appointmentTime: [
            {
              required: true,
              message: "请选择预约时间",
              trigger: "change"
            }
          ]
        },
        kindOptions: [
          {label: "电话", value: "1"},
          {label: "线下", value: "2"},
          {label: "其他", value: "3"}
        ],
        statusOptions: [
          {label: "预约登记", value: "0"},
          {label: "未联系到人", value: "1"},
          {label: "随访登记", value: "2"},
          {label: "预约时间随访", value: "3"}
        ]
      };
    },
    filters: {
      prescriptionKind(t) {
        return app.prescriptionType.map(function (i) {
          if (i.val == t) {
            return i.key;
          }
        })[0];
      },
      timeFormat(t) {
        return new Date(t).Format("yyyy-MM-dd hh:mm:ss");
      },
      kindFormat(s) {
        let status = {1: "电话", 2: "线下", 3: "其他"};
        return status[s];
      },
      statusFormat(s) {
        let status = {
          0: "预约登记",
          1: "未联系到人",
          2: "随访登记",
          3: "预约时间随访"
        };
        return status[s];
      },
      gender(g) {
        return g == 1 ? "男" : "女";
      },
      age(strBirthday) {
        if (strBirthday) {
          let strBirthdayArr = strBirthday.split("-");
          let d = new Date();
          let yearDiff = d.getFullYear() - strBirthdayArr[0];
          let monthDiff = d.getMonth() + 1 - strBirthdayArr[1];
          let dayDiff = d.getDate() - strBirthdayArr[2];
          let age =
            monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)
              ? yearDiff - 1
              : yearDiff;
          //判断有没有到生日,没到就减1
          return age <= 0 ? monthDiff + "月" : age + "岁";
        }
      }
    },
    watch: {
      activeName(val) {
        if (this.activeName === "随访") {
          this.searchFollow();
        }
      }
    },
    methods: {
      BeforeLeave(activeName, oldActiveName) {
        if (oldActiveName && !this.record.finish && activeName !== "随访") {
          if (activeName === "处方" && this.prescription.id) {
            this.addProduct()
          } else {
            let item = this.list[this.tabName.getArrayIndex(oldActiveName)];
            if (item && item.children) {
              let results = [];
              this.checkVal(item, results);
              if (results.length > 0) {
                //自动保存检查数据
                this.validate(item)
              }
            }
          }
        }
        // return true;
      },
      setTemplate(data) {
        let results = [];
        this.getVal(data, results);
        if (results.length > 0) {
          console.log(results)
          saveTemplate(results).then(response => {
            if (response.code === 200) {
              this.$message({
                showClose: true,
                message: "保存模板数据成功",
                type: "success"
              });
            } else {
              this.$message({
                showClose: true,
                message: "保存模板数据失败",
                type: "error"
              });
            }
          })
        }
      },
      checkVal(data, results) {
        let _that = this;
        if (data.children) {
          data.children.forEach(function (item) {
            _that.checkVal(item, results)
          })
        } else {
          if (data.indicatorsActVal !== data.defaulted || (!data.indicatorsActVal && data.defaulted)) {
            if (data.indicatorsActVal) {
              results.push(1)
            }
          }
        }
      },
      getVal(data, results) {
        let _that = this;
        if (data.children) {
          data.children.forEach(function (item) {
            _that.getVal(item, results)
          })
        } else {
          if (data.indicatorsActVal !== data.defaulted || (!data.indicatorsActVal && data.defaulted)) {
            let result = {
              id: data.itemId,
              defaulted: !data.indicatorsActVal ? "" : JSON.stringify(data.indicatorsActVal)
            }
            results.push(result)
          }
        }
      },
      copyVal(data, key) {
        let _that = this;
        if (data.project) {
          key = data.project
        }
        if (data.itemName) {
          key = key + ";" + data.itemName
        }
        if (data.children) {
          data.children.forEach(function (item) {
            _that.copyVal(item, key)
          })
        } else {
          data.indicatorsActVal = _that.map[key]
        }
      },
      validItem(data, key) {
        let _that = this;
        if (data.project) {
          key = data.project
        }
        if (data.itemName) {
          key = key + ";" + data.itemName
        }
        if (data.children) {
          data.children.forEach(function (item) {
            _that.validItem(item, key)
          })
        } else {
          _that.map[key] = data.indicatorsActVal
        }
      },
      hideItem(data) {
        if (data.children) {
          let children = [];
          let _that = this;
          data.children.forEach(function (item) {
            if (item.children) {
              //递归调用
              let child = _that.hideItem(item);
              if (child.children.length > 0) {
                children.push(child);
              }
            } else if (item.indicatorsActVal) {
              children.push(item);
            }
          });
          data.children = children;
        }
        return data;
      },
      setVal(data) {
        if (data.children) {
          let _that = this;
          data.children.forEach(function (item) {
            _that.setVal(item)
          })
        } else {
          try {
            data.indicatorsActVal = (typeof data.val == "string") ? JSON.parse(data.val) : data.val
          } catch (e) {
            data.indicatorsActVal = data.val
          }
        }
      },
      unique(arr) {
        let m = {}
        arr = arr.filter(function (a) {
          if (!m[a.id]) {
            m[a.id] = 1
            return true
          }
          return false
        })
        return arr
      },
      choosePrescription() {
        let m = {}
        this.prescriptionList.forEach(function (i) {
          m[i.projectId] = i.projectName
        })
        let d = []
        this.prescriptionData.forEach(function (i) {
          d.push({
            clinicNo: app.$data.clinicNo,
            info_id: app.$data.targetProjectId,
            indicators_id: i,
            indicators_name: m[i]
          })
        })
        if (d.length === 0) {
          return;
        }
        getInspectInfo(d).then(response => {
          if (response.code === 200) {
            let inspects = getTree(response.page);
            for (let k in inspects) {
              this.list.push(inspects[k])
            }
            this.list = this.unique(this.list)
            this.dialogInspectVisible = false;
          }
        })

      },
      chooseInspect() {
        let m = {}
        this.inspectList.forEach(function (i) {
          m[i.projectId] = i.projectName
        })
        let d = []
        this.inspectData.forEach(function (i) {
          d.push({
            clinicNo: app.$data.clinicNo,
            infoId: i,
            infoName: m[i]
          })
        })
        if (d.length === 0) {
          return;
        }
        getInspectInfo(d).then(response => {
          if (response.code === 200) {
            let inspects = getTree(response.page);
            for (let k in inspects) {
              this.list.push(inspects[k])
            }
            this.list = this.unique(this.list)
            this.dialogInspectVisible = false;
          }
        })

      },
      addMyPrescription(item) {
        this.targetProjectId = item.id;
        this.dialogPrescriptionVisible = true;
      },
      addInspect() {
        this.dialogInspectVisible = true;
      },
      completeTreat() {
        let item = this.list[this.tabName.getArrayIndex(this.activeName)];
        if (item && item.children) {
          let results = [];
          this.checkVal(item, results);
          if (results.length > 0) {
            //自动保存检查数据
            this.validate(item)
          }
        }
        completeTreat({
          clinicNo: this.clinicNo,
          treatId: this.treat
        }).then(response => {
          if (response.code === 200) {
            this.$message({
              showClose: true,
              message: "接诊完成",
              type: "success"
            });
            this.record.finish = true;
          }
        });
      },
      //点击编辑
      handleEdit(index, row) {
        this.$set(this.showEdit, index, true);
        this.$set(this.showBtn, index, true);
      },
      //取消编辑
      handleCancel(index, row) {
        this.$set(this.showEdit, index, false);
        this.$set(this.showBtn, index, false);
      },
      //点击更新
      handleUpdate(index, row) {
      },
      //点击删除
      handleDelete(index, row) {
        this.productList = this.productList.filter(function (item) {
          return item !== row;
        });
      },
      addProduct() {
        let dataResult = {
          productDTOS: [],
          clinicNo: this.clinicNo,
          treatmentId: this.treat,
          prescriptionId: this.prescription.id
        };
        this.productList.forEach(function (item) {
          let p = {
            days: item.days,
            discountPrice: item.discountPrice,
            frequency: item.frequency,
            num: item.needNum,
            part: item.part,
            productCode: item.productCode,
            productName: item.productName,
            singleDose: item.singleDose,
            skuId: item.skuId,
            spuId: item.spuId,
            stockId: item.stockId,
            totalDose: item.totalDose,
            unit: item.unit,
            univalent: item.cost ? item.cost : item.univalent,
            usage: item.usage
          };
          dataResult.productDTOS.push(p);
        });
        console.log(dataResult);
        editPrescriptionStore(dataResult).then(response => {
          if (response.code === 200) {
            this.$message({
              showClose: true,
              message: response.msg,
              type: "success"
            });
          }
        });
      },
      getProduct() {
        this.dialogProductVisible = true;
      },
      submitPrescription() {
        this.prescription.clinicNo = this.clinicNo;
        this.prescription.treatmentId = this.treat;
        makePrescription(this.prescription).then(response => {
          if (response.code === 200) {
            this.$message({
              showClose: true,
              message: response.msg,
              type: "success"
            });
            this.prescription = response.data;
            this.dialogPreVisible = false;
          }
        });
      },
      addPrescription() {
        this.dialogPreVisible = true;
      },
      searchFollow() {
        getFollow({treatmentId: this.treat}).then(response => {
          if (response.code === 200) {
            this.followList = response.page.list;
          }
        });
      },
      submitForm() {
        this.$refs["followForm"].validate(valid => {
          if (!valid) return;
          // TODO 提交表单
          this.followData.treatmentId = this.treat;
          this.followData.parentId = this.patient.id;
          editFollow(this.followData).then(response => {
            if (response.code === 200) {
              this.$message({
                showClose: true,
                message: response.msg,
                type: "success"
              });
              this.dialogVisible = false;
              this.searchFollow();
            }
          });
        });
      },
      onClose() {
        this.resetForm();
      },
      resetForm() {
        this.$refs["followForm"].resetFields();
        this.$refs["prescriptionForm"].resetFields();
        this.$refs["inspectForm"].resetFields();
        this.$refs["prescriptionForm"].resetFields();
        this.dialogInspectVisible = false;
        this.dialogPrescriptionVisible = false;
      },
      validate(data) {
        let _that = this;
        //获取数据到map,后续遍历循环赋值
        data.children.forEach(function (item) {
          _that.validItem(item, "")
        });

        //自动赋值到相同的项目中
        this.list.forEach(function (item) {
          console.log(item === data);
          if (item !== data) {
            _that.copyVal(item, "")
          }
        })

        let result = getResults(data, this.clinicNo, this.patient.id);
        console.log(result);
        //暂时只校验病历
        if (data.seq === 2 && result.validate.length > 0) {
          this.$message({
            showClose: true,
            message: JSON.stringify(result.validate) + " 等字段不能为空",
            type: "error"
          });
          return;
        }
        addTreatResult(result.results).then(response => {
          if (response.code === 200) {
            //增加保存标记
            data.isFinish = 0
            this.$message({
              showClose: true,
              message: response.msg,
              type: "success"
            });
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .el-col.el-col-2 :last-child {
    width: 100% !important;
  }

  .patientInfo {
    margin-top: 5px;
    margin-left: 0 !important;
    color: rgb(156, 159, 165);
    font-size: 14px;
  }

  .social-signup-container {
    margin: 20px 0;
    .sign-btn {
      display: inline-block;
      cursor: pointer;
    }
    .icon {
      color: #fff;
      font-size: 24px;
      margin-top: 8px;
    }
    .wx-svg-container,
    .qq-svg-container {
      display: inline-block;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      padding-top: 1px;
      border-radius: 4px;
      margin-bottom: 20px;
      margin-right: 5px;
    }
    .wx-svg-container {
      background-color: #24da70;
    }
    .qq-svg-container {
      background-color: #6ba2d6;
      margin-left: 50px;
    }
  }
</style>
